<template>
  <div>
    <div class="login-form-title">找回密码</div>
    <a-steps style="margin: 20px 0 0 44px" :current="current" @change="setCurrent">
      <a-step>身份验证</a-step>
      <a-step>密码重置</a-step>
      <a-step>重置完成</a-step>
    </a-steps>
    <div class="head">
      <div style="margin-left: 40px" v-if="current === 1">
        <a-form ref="authRef" :model="authForm" class="login-form" layout="vertical">
          <a-form-item
              field="userName"
              ref="userNameRef"
              :rules="[{ required: true, message: '用户名不能为空' }]"
              :validate-trigger="['change', 'blur']"
              hide-label
          >
            <a-input
                v-model="authForm.userName"
                placeholder="用户名"
                allow-clear
            >
              <template #prefix>
                <icon-user/>
              </template>
            </a-input>
          </a-form-item>
          <a-form-item
              field="code"
              :rules="[{ required: true, message: '邮箱验证码不能为空' }]"
              :validate-trigger="['change', 'blur']"
              hide-label
          >
            <a-input
                v-model="authForm.code"
                placeholder="邮箱验证码"
                allow-clear
            >
              <template #prefix>
                <icon-email/>
              </template>
              <template #append>
                <a-button :disabled="flag" type="primary" size="10" @click="getAuthCode">{{ msg }}</a-button>
              </template>
            </a-input>
          </a-form-item>
        </a-form>
        <a-space size="large" style="margin-top: 30px">
          <a-button type="secondary" :disabled="current <= 1" @click="onAuthPrev">
            <IconLeft/>
            上一步
          </a-button>
          <a-button type="primary" html-type="submit" :disabled="current >= 3" @click="onAuthNext">
            下一步
            <IconRight/>
          </a-button>
        </a-space>
      </div>
      <div style="margin-left: 40px" v-else-if="current === 2">
        <a-form ref="passwordFormRef" :model="passwordForm" layout="vertical">
          <a-form-item
              field="password"
              :rules="[
                  { required: true, message: '密码不能为空' },
                  { match: RegExp('^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!#$%^&*])[\\da-zA-Z!#$%^&*]{8,16}$'),message: '用户密码长度必须介于8和16之间且包含数字,大小写字母,特殊字符'},
                  ]"
              :validate-trigger="['change', 'blur']"
              hide-label
          >
            <a-input-password
                v-model="passwordForm.password"
                placeholder="密码"
                allow-clear
            >
              <template #prefix>
                <icon-lock/>
              </template>
            </a-input-password>
          </a-form-item>
          <a-form-item
              field="confirmPassword"
              :rules="[
                  { required: true, message: '确认密码不能为空' },
                  { required: true, validator: equalToPassword }
                  ]"
              :validate-trigger="['change', 'blur']"
              hide-label
          >
            <a-input-password
                v-model="passwordForm.confirmPassword"
                placeholder="确认密码"
                allow-clear
            >
              <template #prefix>
                <icon-lock/>
              </template>
            </a-input-password>
          </a-form-item>
        </a-form>
        <a-space size="large" style="margin-top: 30px">
          <a-button type="secondary" :disabled="current <= 1" @click="onResetPrev">
            <IconLeft/>
            上一步
          </a-button>
          <a-button type="primary" html-type="submit" :disabled="current >= 3" @click="onResetNext">
            下一步
            <IconRight/>
          </a-button>
        </a-space>
      </div>
      <div style="margin-left: 40px" v-else>
        <div style="color: black"> -^0^-新登录密码重置成功，请重新登录</div>
        <a-space size="large">
          <a-button type="primary" style="margin-top: 60px" @click="$emit('passpwd',false)">
            重新登录
          </a-button>
        </a-space>
      </div>

    </div>
  </div>
</template>
<script setup>
import { sendCode,verifyCode,resetPwd } from "@/api/login";
import {getCurrentInstance, reactive, ref} from "vue";
const current = ref(1);
const {proxy} = getCurrentInstance();
const flag = ref(false)
const msg = ref("获取验证码")
const defaultUserId = ref("");
const defaultUserName = ref("");

const data = reactive({
  authForm: {},
  passwordForm: {},
  queryParam:{}
})

const {authForm, passwordForm,queryParam} = toRefs(data);


function onAuthPrev() {
  current.value = Math.max(1, current.value - 1)
}

function onAuthNext() {
  proxy.$refs["authRef"].validate(valid => {
    if (!valid) {
      verifyCode(authForm.value).then(res=>{
        current.value = Math.min(3, current.value + 1)
      }).catch(error => {
        console.log(error)
      })
    }
  });
}

function onResetPrev() {
  current.value = Math.max(1, current.value - 1)
}

function onResetNext() {
  proxy.$refs["passwordFormRef"].validate(valid => {
    if (!valid) {
      passwordForm.value.userId = defaultUserId.value;
      passwordForm.value.userName = defaultUserName.value;
      resetPwd(passwordForm.value).then(res=>{
        current.value = Math.min(3, current.value + 1)
      }).catch(error => {
        console.log(error)
      })
    }
  });
}

function setCurrent(cur) {
  current.value = cur
}

const equalToPassword = (value, callback) => {
  if (passwordForm.value.password !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

async function getAuthCode() {
  proxy.$refs["authRef"].validateField('userName', valid => {
    if (!valid) {
      queryParam.value.userName = authForm.value.userName
      sendCode(queryParam.value).then(res=>{
        defaultUserId.value = res.data.userId
        defaultUserName.value = res.data.userName
          //获取验证码按钮倒计时功能的实现
          flag.value = true; // 按钮不可重复点击
          let time = 120; //定义时间变量 120s
          let timer = null; //定义定时器
          timer = setInterval(function () {
            if (time === 0) {
              msg.value = "重新获取验证码";
              flag.value = false;
              clearInterval(timer);//清除定时器
            } else {
              msg.value = time + "秒后重新获取";
              time--;
            }
          }, 1000)
      }).catch(error => {
        console.log(error)
      })
    }
  });
}

</script>

<style lang="less" scoped>
.login-form {
  &-wrapper {
    width: 320px;
  }

  &-title {
    margin-left: 48px;
    color: var(--color-text-1);
    font-weight: 500;
    font-size: 24px;
    line-height: 32px;
  }

  &-sub-title {
    color: var(--color-text-3);
    font-size: 16px;
    line-height: 24px;
  }

  &-error-msg {
    height: 32px;
    color: rgb(var(--red-6));
    line-height: 32px;
  }

  &-password-actions {
    display: flex;
    justify-content: space-between;
  }

  &-register-btn {
    color: var(--color-text-3) !important;
  }

  .login-code {
    width: 37%;
    height: 36px;
    float: right;
    padding-left: 30px;
    padding-top: 2px;

    img {
      cursor: pointer;
      vertical-align: middle;
    }
  }

  .login-code-img {
    height: 32px;
  }
}

.head {
  width: 100%;
  height: 200px;
  padding: 10px;
  text-align: center;
  background: var(--color-bg-2);
  color: #C2C7CC;
  margin-top: 20px;
}
</style>

